#!/usr/bin/env node
const { program } = require("commander");
const path = require("path");
const fs = require("fs-extra");
const c = require("ansi-colors");

const {
  generateImageUrl,
  downloadAjax,
  readAllFiles,
  generateDownloadPathList,
  writeObjectToModule,
} = require("./utils/index.js");
const allEmojiData = require("./data.js");

// 设置程序版本
program.version("1.0.0");

// 定义一个子命令 download
program
  .command("download [types...]")
  .description(
    "Download file from [ people , nature , food , activity , travel , objects , symbols , flags ] "
  )
  .option("-d, --directory <path>", "Output directory", "downloads")
  .option("-o, --origin <url>", "input your origin url")
  .action(async (types, { directory, origin }) => {
    try {
      const configContent = {};
      const configFilePath = path.join(process.cwd(), `${directory}/config.js`);
      await fs.remove(configFilePath);
      let typeList = [];
      console.log(
        c.green("-----------------------开始执行！-----------------------\n\n")
      );
      if (types.length) {
        typeList = [...types];
        for (let emojiType of types) {
          let filePath = path.join(process.cwd(), `${directory}/${emojiType}`);
          await fs.remove(filePath);
          await fs.ensureDir(filePath);
          await Promise.all(
            allEmojiData[emojiType].map((item) => {
              const url = generateImageUrl(emojiType, item);
              return downloadAjax(url, filePath);
            })
          );
        }
      } else {
        for (const emojiType of Object.keys(allEmojiData)) {
          typeList.push(emojiType);
          let filePath = path.join(process.cwd(), `${directory}/${emojiType}`);
          await fs.remove(filePath);
          await fs.ensureDir(filePath);
          await Promise.all(
            allEmojiData[emojiType].map((item) => {
              const url = generateImageUrl(emojiType, item);
              return downloadAjax(url, filePath);
            })
          );
        }
      }
      const emojiOptions = generateDownloadPathList(typeList, directory);
      for (let option of emojiOptions) {
        configContent[option.emojiType] = await readAllFiles(
          option.filePath,
          origin
        );
      }
      await writeObjectToModule(configContent, configFilePath);
      fs.writeFileSync(
        `${directory}/index.html`,
        fs.readFileSync(path.join(__dirname, `config.html`), "utf8")
      );
      console.log(
        c.green.bold(
          `\n执行完成，点击查看效果： ${c.white.bold.underline(
            `${path.join(process.cwd(), `${directory}/index.html`)}`
          )}`
        )
      );
    } catch (error) {
      console.error(`${c.red(`执行失败：${error.message}`)}`);
      process.exit(1);
    }
  });

// 解析命令行参数
program.parse(process.argv);
